import re

class Paginator():
    def __init__(self,allrecords,pagesize):
        self.allrecords = allrecords
        if 'all' not in dir(allrecords):
            self.count = len(allrecords)
        else:
            self.count = allrecords.count()
        self.pagesize = pagesize
        self.current_index = None
        self.pagecount = None
        self.object_list = None
        self.hasnext = False
        self.hasprevious = False
        self.next = 1
        self.previous = 1

    def page(self, pageindex):
        if self.count % self.pagesize == 0:
            if self.count == 0:
                self.pagecount=1
            else:
                self.pagecount = self.count/self.pagesize
        else:
            self.pagecount = (self.count - self.count % self.pagesize)/self.pagesize + 1

        pageindex = max(min(pageindex, self.pagecount), 0)
        self.current_index = pageindex

        if self.current_index != self.pagecount:
            self.hasnext = True
            self.next = self.current_index + 1
        if self.current_index != 1:
            self.hasprevious = True
            self.previous = self.current_index - 1

        self.object_list = self.allrecords[(pageindex-1)*self.pagesize:(pageindex*self.pagesize)]
        return self

    def page_from_url(self, url):
    #find the pageindex
        re_pageindex = re.compile('pageindex\d+')
        pageindex_list = re_pageindex.findall(url)
        if len(pageindex_list) > 0:
            self.page(int(pageindex_list[0].replace('pageindex','')))
        else:
            self.page(1)

    def get_page_url(self, url, index):
        re_pageindex = re.compile('pageindex\d+')
        pageindex_list = re_pageindex.findall(url)
        if len(pageindex_list) > 0:
            return url.replace(pageindex_list[0], 'pageindex%s' % index)
        else:
            return url + (url.find('?')>=0 and '&' or '?') + 'page=' +  'pageindex%s' % index

